import { Injectable } from '@nestjs/common';
import { CreateApprovalNodeDto } from './dto/create-approval_node.dto';
import { UpdateApprovalNodeDto } from './dto/update-approval_node.dto';
import {InjectRepository} from "@nestjs/typeorm";
import {ApprovalNode} from "./entities/approval_node.entity";
import { Repository} from "typeorm";
import {ApprovalStatusEnum} from "../../constant/ApprovalStatusEnum";

@Injectable()
export class ApprovalNodeService {
  constructor(@InjectRepository(ApprovalNode) private readonly approvalNodeRepository: Repository<ApprovalNode>) {
  }
  create(createApprovalNodeDto: CreateApprovalNodeDto) {
    return this.approvalNodeRepository.save(createApprovalNodeDto);
  }

  findAll() {
    return this.approvalNodeRepository.find();
  }

  findOne(id: string) {
    return this.approvalNodeRepository.findOne({
      where: {
        id
      }
    });
  }

  update(id: string, updateApprovalNodeDto: UpdateApprovalNodeDto) {
    return this.approvalNodeRepository.update(id, updateApprovalNodeDto);
  }

  remove(id: string) {
    return this.approvalNodeRepository.delete(id);
  }

  /**
   * 开启事务,保存所有节点信息
   */
  saveAllNode(nodes: CreateApprovalNodeDto[]){
    const saveEntity = []
    // 1. 根据前端信息循环生成对象
    nodes.forEach(node => saveEntity.push(this.approvalNodeRepository.create(node)));
    const elen = saveEntity.length;
    if ( elen> 0){
      // 2.给 head, trail 赋值
      const headId = saveEntity[0].id;
      const trailId = saveEntity[elen-1].id
      for(let idx=0; idx<elen; idx++){
        // 2.1 给next 赋值
        let next = idx < (elen-1) ? saveEntity[idx+1] : null;
        saveEntity[idx].head = headId;
        saveEntity[idx].trail = trailId;
        saveEntity[idx].next = next;
      }
      // 3.开启事务批量保存
      return this.approvalNodeRepository.save(saveEntity);
    }



  }

  updateStatus(id:string, status:number){
    const updateApprovalNodeDto = new UpdateApprovalNodeDto;
    updateApprovalNodeDto.status = status;
    return this.update(id, updateApprovalNodeDto);
  }

  /**
   * 同意节点,将节点状态设置为ApprovalStatusEnum.AGREE(1)
   */
  agreeNode(id: string){
      return this.updateStatus(id, ApprovalStatusEnum.AGREE)
  }

  /**
   * 撤回,驳回审批结果重置,将相同head的status设置成ApprovalStatusEnum.SUBMIT(0)状态
   * TODO 改进方法, 开启事务,进行批量更新
   */
  restoreStatus(head: string){
    return this.approvalNodeRepository.find({where:{head}}).then(value => {
      value.forEach(node=>{
        node.status = ApprovalStatusEnum.SUBMIT;
        // TODO 将逐条更新改为批量更新
        this.approvalNodeRepository.update(node.id, node).then()
      })
    })
  }



  /**
   * 结束节点, 将尾节点状态设置为ApprovalStatusEnum.REFUSE(2)
   */
  endNode(id: string){
    return this.updateStatus(id, ApprovalStatusEnum.REFUSE)
  }


}
